package com.imooc.utils;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.imooc.config.SmsTemplateIDEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Set;
import java.util.UUID;


@Component
public class SMSUtils {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    private static final Logger LOGGER= LoggerFactory.getLogger(SMSUtils.class);

    /**
     * 模拟发送短信过程，感兴趣的朋友可以尝试对接一些第三方的短信平台
     *
     * @param phone
     * @param code
     */
    private boolean sendSmsToCcp(String phone, Integer code) {
        LOGGER.info("phone is {},code is {}", phone, code);
        //测试环境就不发送短信了，节省话费
//        if(namespace.contains("test")){
//            return true;
//        }
        try {
            //生产环境请求地址：app.cloopen.com
            String serverIp = tencentCloudProperties.getSmsServerIp();
            //请求端口
            String serverPort = tencentCloudProperties.getPort();
            //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
            String accountSId = tencentCloudProperties.getAccountSId();
            String accountToken = tencentCloudProperties.getAccountToken();
            //请使用管理控制台中已创建应用的APPID
            String appId = tencentCloudProperties.getAppId();
            CCPRestSmsSDK sdk = new CCPRestSmsSDK();
            sdk.init(serverIp, serverPort);
            sdk.setAccount(accountSId, accountToken);
            sdk.setAppId(appId);
            sdk.setBodyType(BodyType.Type_JSON);
            String to = "15730125495";
            String templateId= SmsTemplateIDEnum.SMS_LOGIN_CODE_TEMPLATE.getTemplateId();
            String[] datas = {String.valueOf(code),"1"};
            String subAppend="1234";  //可选 扩展码，四位数字 0~9999
            String reqId= UUID.randomUUID().toString();  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
            //HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
            HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);
            System.out.println("短信验证码为"+code);
            if("000000".equals(result.get("statusCode"))){
                //正常返回输出data包体信息（map）
                HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
                Set<String> keySet = data.keySet();
                for(String key:keySet){
                    Object object = data.get(key);
                    LOGGER.info("key is {},object is {}",key,object);
                }
            }else{
                //异常返回输出错误码和错误信息
                LOGGER.info("sendSmsToCcp 错误码为：{}，错误信息是：{}",result.get("statusCode"),result.get("statusMsg"));
            }
            return true;
        } catch (Exception e) {
            LOGGER.error("[sendSmsToCcp] error is",e);
            throw new RuntimeException(e);
        } finally {
            return false;
        }
    }
}
